import pymysql

from weixin.config import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_PORT, MYSQL_DATABASE


class Mysql():

    def __init__(self, host=MYSQL_HOST, username=MYSQL_USER, password=MYSQL_PASSWORD, port=MYSQL_PORT,
                 database=MYSQL_DATABASE):
        """
        数据库初始化
        :param host:
        :param username:
        :param port:
        :param database:
        """
        try:
            self.db = pymysql.connect(host=host, user=username, password=password, port=port, db=database)
            self.cursor = self.db.cursor()
        except pymysql.MySQLError as e:
            print(e.args)

    def insert(self,table,data):
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
        try:
            if self.cursor.execute(sql, tuple(data.values())):
                print('Successful')
                self.db.commit()
        except:
            print('Failed')
            self.db.rollback()

    def db_close(self):
        self.db.close()
